package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.enviaEmail;
import bean.OSBean;
import bean.secretarioBean;
import conexao.Conexao;
import dao.OSDao;
import dao.secretarioDao;

public class alterarOsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
    public alterarOsServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		
		PrintWriter out = response.getWriter();
		
		Connection conn = null;
		try {
			conn = new Conexao().getConexao();
		} catch (SQLException e) {
			new enviaEmail().enviar(e);
			out.print("falhaConexao");
			return;
		}
		
		Integer id = Integer.parseInt(request.getParameter("idOS"));
		String situacao = request.getParameter("novaOsSituacao");
		String descricao = "";
		
		if (request.getParameter("novaOsSelCliente") == "") {
			out.println("Por favor selecione um cliente.");
			return;
		}else if (request.getParameter("novaOsValor") == "") {
			out.println("Informe o valor da OS.");
			return;
		}else if (request.getParameter("novaOsTextarea") == "" && situacao.equals("novaOS")) {
			out.println("A descrição não pode ser vazio.");
			return;
		}else{		
			Integer idCliente = Integer.parseInt(request.getParameter("novaOsSelCliente"));	
			Double valor = Double.parseDouble(request.getParameter("novaOsValor").replace(",", "."));	
			if(situacao.equals("novaOS")){
				descricao = request.getParameter("novaOsTextarea");	
			}
			Integer idSecretario = Integer.parseInt(request.getParameter("novaOsIdFuncionario"));
			String urgen = request.getParameter("urgente");
			int urgente = 0;
			if(urgen != null){
				urgente = 1;
			}
			SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
			SimpleDateFormat sdfBra = new SimpleDateFormat("dd/MM/yyyy");
			long prazoEntrega = 0;
			try {
				if(request.getParameter("novaOsPrazoHora") != "" && request.getParameter("novaOsPrazoDia") != ""){
					prazoEntrega = sdf.parse(request.getParameter("novaOsPrazoDia")+" "+request.getParameter("novaOsPrazoHora")+":00").getTime();
				}else if(request.getParameter("novaOsPrazoHora") == "" && request.getParameter("novaOsPrazoDia") != ""){
					prazoEntrega = sdf.parse(request.getParameter("novaOsPrazoDia")+" 00:00:00").getTime();
				}else if(request.getParameter("novaOsPrazoHora") != "" && request.getParameter("novaOsPrazoDia") == ""){
					prazoEntrega = sdf.parse(sdfBra.format(new Date())+" "+request.getParameter("novaOsPrazoHora")+":00").getTime();
				}
			} catch (ParseException e) {
				new enviaEmail().enviar(e);
				out.println("Data ou Hora inválida.");
				return;
			} 
		
			OSBean OS = new OSBean();
			OS.setId(id);
			OS.setIdCliente(idCliente);
			OS.setDescricao(descricao);
			OS.setValor(valor);
			OS.setUrgente(urgente);
			if(prazoEntrega != 0){
				OS.setPrazoEntrega(new Timestamp(prazoEntrega));
			}		
			
			secretarioBean secBean = new secretarioBean();
			secBean.setIdsecretario(idSecretario);
			secBean.setIdos(id);
			
			try {
				
				new OSDao().alterar(conn, OS);
				new secretarioDao().alterar(conn, secBean);
				conn.commit();
				
			} catch (Exception e) {
				try {
					conn.rollback();
				} catch (Exception ex) {
					new enviaEmail().enviar(ex);
					ex.printStackTrace();
				}
				new enviaEmail().enviar(e);
				throw new RuntimeException(e);
			} finally {
				try {
					conn.close();
				} catch (Exception ex) {
					new enviaEmail().enviar(ex);
				}
			}
		}
	}
}